//
//  File.swift
//  LocationTrackerAdmin
//
//  Created by mac on 2025/3/25.
//

import Foundation
import Vapor
import FluentKit
import AppStoreServerLibrary
struct AppStoreNotification: RouteCollection {
    func boot(routes: any Vapor.RoutesBuilder) throws {
        let group = routes.grouped("appstore")
        group
            .post("notifications", use: self.handleNotification)
    }
    
    @Sendable
    func handleNotification(request: Request) async throws -> Response {
        struct Payload: Content {
            let signedPayload: String
        }
        let signedPayload = try request.content.decode(Payload.self)
        let result = try await request.application.appstore.handleSubscriptionChange(jwt: signedPayload.signedPayload)
        let orderInfo = result.data?.signedTransactionInfo ?? ""
        let detail = try await request.application.appstore.extractOrderTransaction(signedInfo: orderInfo)
        let userID = (detail.appAccountToken?.uuidString ?? "").replacingOccurrences(of: "-", with: "")
        switch result.notificationType {
        case .subscribed:
            try await UserModel.query(on: request.db)
                .filter(\.$id == userID)
                .set(\.$isVIP, to: true)
                .set(\.$vipExpireDate, to: detail.expiresDate)
                .update()
            break
        case .didRenew:
            try await UserModel.query(on: request.db)
                .filter(\.$id == userID)
                .set(\.$isVIP, to: true)
                .set(\.$vipExpireDate, to: detail.expiresDate)
                .update()
            break
        case .didChangeRenewalStatus:
            break
        case .expired:
            try await UserModel.query(on: request.db)
                .filter(\.$id == userID)
                .set(\.$isVIP, to: false)
                .update()
            break
        case .refund:
            try await UserModel.query(on: request.db)
                .filter(\.$id == userID)
                .set(\.$isVIP, to: false)
                .update()
            break
        case .didChangeRenewalPref:
            try await UserModel.query(on: request.db)
                .filter(\.$id == userID)
                .set(\.$isVIP, to: true)
                .set(\.$vipExpireDate, to: detail.expiresDate)
                .update()
            break
        case .revoke:
            break
        case .gracePeriodExpired:
            //试用结束
            try await UserModel.query(on: request.db)
                .filter(\.$id == userID)
                .set(\.$isVIP, to: false)
                .update()
            break
        default:
            break
        }
        let model = SubscriptionRecordModel(from: detail)
        try await model.save(on: request.db)
        return Response(status: .ok)
    }
    
}
